package com.android.ailaoshan.picture;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

/**
 * 拍照完成后图片处理
 * 图片预处理
 */
public class DealPicture {

    private final String PIC_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator +"AiLaoShan"+ File.separator + "Picture" + File.separator;

    /**
     * 拍照完成后处理
     */
    public void donePicture(int RESULT_CODE, String picName, Context context){
        // 文件名截取
        int index = picName.lastIndexOf(File.separator);
        String picNameX = picName.substring(index+1);
        String picPath = PIC_PATH + picNameX;

        File file = new File(picPath);
        if(file.exists() && file.isFile()){
            // 拍照成功
            if(RESULT_CODE == -1){
                // 防止出现空文件
                if(file.length() == 0){
                    Toast.makeText(context,"当前拍照图片已损坏，重新拍一张试试",Toast.LENGTH_SHORT).show();
                    file.delete();
                }else{
                    // 跳转Activity
                    ArrayList<String> pictures = new ArrayList<>();
                    pictures.add(picNameX);
                    Intent intent = new Intent(context,PictureActivity.class);
                    intent.putStringArrayListExtra("picName",pictures);
                    intent.putExtra("saveType",1);
                    context.startActivity(intent);
                }
            }else{
                file.delete();
            }
        }
        // 删除空文件
        deleteNullFile();
    }


    /**
     * 删除空文件
     */
    private void deleteNullFile(){
        new Thread(
            ()->{
                // 生成图片文件夹目录
                File folder = new File(PIC_PATH);

                // 获取目录下所有文件
                File[] files = folder.listFiles();
                if(files != null){
                    for(File file : files){
                        // 文件大小为0，删除
                        if(file.length() == 0){
                            file.delete();
                        }
                    }
                }
            }
        ).start();
    }


    /**
     * 从相册复制文件到目标目录
     */
    void copyImageFile(Intent data,Context context,PictureActivity.MyHandler handler){
        new Thread(
            () -> {
                Uri imageUri = data.getData();
                String[] filePathArray = {MediaStore.Images.Media.DATA};

                // 从系统表中查询指定URI对应的图片
                if(imageUri != null){
                    Cursor cursor = context.getContentResolver().query(imageUri,filePathArray,null,null,null);
                    if(cursor != null){
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathArray[0]);
                        String path = cursor.getString(columnIndex);
                        cursor.close();

                        // 路径不为空
                        if( !path.equals("") ){
                            File file = new File(path);
                            if(file.exists()){
                                try {
                                    FileInputStream inputStream = new FileInputStream(path);

                                    // 判断目标文件夹是否存在
                                    File targetFolder = new File(PIC_PATH);
                                    if( !targetFolder.exists() ){
                                        targetFolder.mkdirs();
                                    }

                                    // 创建目标文件
                                    String newFileName = System.currentTimeMillis() + ".jpg";
                                    String targetPath = PIC_PATH+ newFileName;
                                    File targetFile = new File(targetPath);
                                    boolean createFileSuccess = true;
                                    if( !targetFile.exists() ){
                                        createFileSuccess = targetFile.createNewFile();
                                    }

                                    if(createFileSuccess){
                                        FileOutputStream outputStream = new FileOutputStream(targetFile);
                                        byte[] bytes = new byte[1024];
                                        int byteRead;
                                        while ( (byteRead = inputStream.read(bytes)) != -1){
                                            outputStream.write(bytes,0,byteRead);
                                        }
                                        inputStream.close();
                                        outputStream.close();

                                        Message msg = handler.obtainMessage();
                                        msg.what = 204;
                                        msg.obj = newFileName;
                                        handler.sendMessage(msg);
                                    }
                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            }
                        }
                    }
                }
            }
        ).start();
    }
}
